﻿using HelixToolkit.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;

namespace QuickStart_Project_01.Model3Ds
{
    public class ChimneyModel3D : Visual3Dobjet
    {
        GeometryModel3D whiteBands = new GeometryModel3D();
        GeometryModel3D redBands = new GeometryModel3D();

        public ChimneyModel3D()
        {
            whiteBands.Material = MaterialHelper.CreateMaterial(Colors.White, 0.5);
            redBands.Material = MaterialHelper.CreateMaterial(Colors.Red, 0.5);

            this.InitModel();

            Model3DGroup group = new Model3DGroup();
            group.Children.Add(whiteBands);
            group.Children.Add(redBands);
            this.Visual3DModel = group;
        }

        public override void Selected(bool selected)
        {
            double opacity = 0.5;
            if (selected)
            {
                opacity = 1;
            }
            whiteBands.Material = MaterialHelper.CreateMaterial(Colors.White, opacity);
            redBands.Material = MaterialHelper.CreateMaterial(Colors.Red, opacity);
        }

        private void InitModel()
        {
            double height = 80;
            double baseDiameter = 6;
            double topDiameter = 3;
            int bandsCount = 8;

            var white_builder = new MeshBuilder(false, false);
            var red_builder = new MeshBuilder(false, false);
            for (int i = 0; i < bandsCount; i++)
            {
                var f0 = (double)i / bandsCount;
                var f1 = (double)(i + 1) / bandsCount;
                var y0 = height * f0;
                var y1 = height * f1;
                // 正确的插值写法
                var d0 = (baseDiameter * (1 - f0)) + (topDiameter * f0);
                // 错误的插值写法
                // var d0 = (baseDiameter * (1 - f0)) + topDiameter;
                //    当 f0 = 1 时，得到：d0 = 0 + topDiameter = topDiameter（正常）
                //    当 f0 = 0 时，得到：d0 = baseDiameter + topDiameter（错误）
                var d1 = (baseDiameter * (1 - f1)) + (topDiameter * f1);

                var builder = (bandsCount - i) % 2 == 1 ? red_builder : white_builder;
                builder.AddCone(new Point3D(0, 0, y0), 
                    new Vector3D(0, 0, 1), 
                    d0 / 2, 
                    d1 / 2, 
                    y1 - y0,
                    i == 0, 
                    i == bandsCount - 1, 
                    40);
            }

            this.redBands.Geometry = red_builder.ToMesh();
            this.whiteBands.Geometry = white_builder.ToMesh();
        }
    }
}
